package com.estronger.shopmanage.ui.measure.pg;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.pull_to_refresh_expandablelist.CommonFooterView;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshBase;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshListView;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.adapter.dateAdapter;
import com.estronger.shopmanage.adapter.tasking.DesignerTripAdapter;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.DesignerTrip;
import com.estronger.shopmanage.bean.choiseDateEntity;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.utils.BeforeOrAfterDate;
import com.estronger.shopmanage.utils.NetUtils;
import com.estronger.shopmanage.utils.TimeUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.CircularProgress;
import com.lidroid.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by Soonfor on 2017/5/17.
 */

public class MsPGTripActivity  extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ListView> {

    private RelativeLayout rl_root;// 根布局view
    private List<choiseDateEntity> mSimpleListValues;
    private Context mContext;
    private dateAdapter adapter;
    private GridView gridview;
    protected PullToRefreshListView mListView;
    protected CircularProgress bar;
    protected TextView empty_view;
    ArrayList<DesignerTrip.DesignerTripData> data;
    private DesignerTripAdapter dta;
    private TextView selecttime;
    private int perposion = 0;
    private int curpostion = 0;
    private String pddate;

    // 初始化各个View
    @Override
    protected void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        rl_root = (RelativeLayout) View.inflate(this,
                R.layout.activity_pg_ms_trip, null);
        setContentView(rl_root);
        mContext = MsPGTripActivity.this;

        selecttime = (TextView)rl_root.findViewById(R.id.selecttime);
        selecttime.setText(TimeUtils.getSystime("yyyy年MM月")+"");
        mSimpleListValues = new ArrayList<choiseDateEntity>();
        BeforeOrAfterDate bd = new BeforeOrAfterDate();
        long nowDate = System.currentTimeMillis();
        for (int i = 0; i < 15; i++) {
            choiseDateEntity c = new choiseDateEntity();
            String date = bd.beforNumDay(new Date(nowDate), i);
            c.setTruedate(date);
            c.setDate(date.substring(date.lastIndexOf("-") + 1,date.length()));
            c.setPic(BitmapFactory.decodeResource(getResources(),R.drawable.u29));
            mSimpleListValues.add(c);
        }
        gridview = (GridView) rl_root.findViewById(R.id.date_gridview);
        adapter = new dateAdapter(this, mSimpleListValues,listener);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int size = mSimpleListValues.size();//要显示数据的个数
        //gridview的layout_widht,要比每个item的宽度多出2个像素，解决不能完全显示item的问题
        int allWidth = (int) (58 * size * density);
        int itemWidth = (int) (56 * density);//每个item宽度
        LinearLayout.LayoutParams params = new
                LinearLayout.LayoutParams(allWidth,itemWidth);
        gridview.setLayoutParams(params);
        gridview.setColumnWidth(itemWidth);
        gridview.setHorizontalSpacing(3);
        gridview.setStretchMode(GridView.NO_STRETCH);
        gridview.setNumColumns(size);

        gridview.setAdapter(adapter);
        adapter.setindex(0);
        adapter.notifyDataSetChanged();

//        //解决gridview上下滑动的问题
//        gridview.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                    case MotionEvent.ACTION_MOVE:
//                        v.getParent().requestDisallowInterceptTouchEvent(false);
//                        break;
//                    case MotionEvent.ACTION_UP:
//                    case MotionEvent.ACTION_CANCEL:
//                        v.getParent().requestDisallowInterceptTouchEvent(false);
//                        break;
//                }
//                return true;
//            }
//        });

        mListView = (PullToRefreshListView) rl_root.findViewById(R.id.success_listview);
        mListView.setOnRefreshListener(this);
        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        mListView.setState(CommonFooterView.State.HIDE);

        //获得数据
        dta = new DesignerTripAdapter(mContext,data);
        mListView.setAdapter(dta);
        bar = (CircularProgress) rl_root.findViewById(R.id.loding_view);
        empty_view = (TextView) rl_root.findViewById(R.id.empty_view);

        bar.setVisibility(View.VISIBLE);

        pddate = TimeUtils.getSystime("yyyy-MM-dd");
        loadData(pddate);
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String date = (String)v.getTag().toString().split("::")[0];
            curpostion = Integer.parseInt((String)v.getTag().toString().split("::")[1]);
            adapter.resetBg(gridview,curpostion,perposion);
            perposion = Integer.parseInt((String)v.getTag().toString().split("::")[1]);
            selecttime.setText(date.split("-")[0]+"年"+date.split("-")[1]+"月");
            pddate = date;
            loadData(pddate);
            bar.setVisibility(View.VISIBLE);

        }
    };

    public void connect(String pddate) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("sf_action", "getassignschedule");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("querypidate", pddate);
        netManager.connectWork(params, NetManager.MEASURE_TRIP);
    }

    protected NetManager netManager = new NetManager() {
        @Override
        public void onNetWorkErorr(int code, String result) {
            if (null != mListView) {
                mListView.setState(CommonFooterView.State.HIDE);
                if (null != bar)
                    bar.setVisibility(View.GONE);
                mListView.onRefreshComplete();
                if (data.size() == 0) {
                    empty_view.setVisibility(View.VISIBLE);
                }
            }
        }

        @Override
        public void onNetWorkSuccess(int code, String result) {
            if (null != bar)
                bar.setVisibility(View.GONE);
            if (null != mListView) {
                mListView.setState(CommonFooterView.State.HIDE);
                mListView.onRefreshComplete();
                if (code == NetManager.MEASURE_TRIP) {
                    DesignerTrip bean = gson.fromJson(result, DesignerTrip.class);
                    if (bean.success) {
                        if (bean.data != null && bean.data.size() > 0) {
                            empty_view.setVisibility(View.GONE);
                            data = bean.data;
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    dta = new DesignerTripAdapter(mContext,data);
                                    mListView.setAdapter(dta);
                                }
                            },100);
                        }
                        if (bean.data.size() == 0) {
                            empty_view.setVisibility(View.VISIBLE);
                            dta = new DesignerTripAdapter(mContext,new ArrayList<DesignerTrip.DesignerTripData>());
                            mListView.setAdapter(dta);
                        }
                    } else {
                        empty_view.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
    };

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        loadData(pddate);
    }

    protected void loadData(final String pddate) {
        if (!NetUtils.isNetworkConnected(this)) {
            Toast.show(this, "网络链接已断开！", 2000);
        } else {
            MyApplication.getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    connect(pddate);
                }
            }, 100);
        }
    }
}
